﻿#pragma execution_character_set("utf-8")

#include "logprint.h"
#include <windows.h>

//auto gLevel = LgLevel::LL_Error| LgLevel::LL_Warn |LgLevel::LL_Info;
//auto gLevel = LgLevel::LL_None;
//auto gLevel = LgLevel::LL_Test;
auto gLevel = LgLevel::LL_All;
//auto gLevel = LgLevel::LL_Error;
//auto gLevel = LgLevel::LL_Test|LgLevel::LL_Info;

//PrintDebugView PrintDebugView::single;

void DPA(LgLevel lev, const char *fmt, ...)
{
    if (lev & gLevel)
    {
        char buf[2048], *p = buf;
        va_list args;

        va_start(args, fmt);

        auto size = sizeof(buf);

        p += vsnprintf_s(p, size, _TRUNCATE, fmt, args);
        va_end(args);

        while (p > buf && isspace(p[-1]))
            *--p = '\0';
        *p++ = '\r';
        *p++ = '\n';
        *p = '\0';

        //PrintDebugView::single.PushString(std::string(buf));

        OutputDebugStringA(buf); //OutputDebugString
        printf(buf);
    }
}

void DPW(LgLevel lev, const wchar_t *fmt, ...)
{
    if (lev & gLevel)
    {
        wchar_t buf[2048], *p = buf;
        va_list args;

        va_start(args, fmt);
        auto size = sizeof(buf) / sizeof(wchar_t);
        p += _vsnwprintf_s(p, size, _TRUNCATE, fmt, args);
        va_end(args);

        while (p > buf && isspace(p[-1]))
            *--p = '\0';
        *p++ = '\r';
        *p++ = '\n';
        *p = '\0';

        OutputDebugString(buf); //OutputDebugString
        wprintf(buf);
    }
}

CallbackLogInfo LogInfoChinese::OnAppend = nullptr;

void LogInfoChinese::append(LgLevel lv, std::wstring info)
{
    if (OnAppend)
    {
        std::wstring type = L"[警告]: ";
        switch (lv)
        {
        case LL_Error:
            type = L"[错误]: ";
            break;
        case LL_Info:
            type = L"[提示]: ";
            break;
        }

        OnAppend(type + info);
    }
}

void PrintDebugView::PushString(std::string line)
{
    std::lock_guard<std::mutex> lg(mLockQueStr);
    mQueueStr.push(line);
}

void PrintDebugView::PushWString(std::wstring line)
{
}

void PrintDebugView::thread_func()
{
    std::string pop_one;
    bool IsLog = true;

    do
    {
        if (!IsLog)
            std::this_thread::sleep_for(std::chrono::milliseconds(500));

        {
            std::lock_guard<std::mutex> lg(mLockQueStr);

            if (mQueueStr.size() < 1)
            {
                IsLog = false;
                continue;
            }
            pop_one = mQueueStr.front();
            mQueueStr.pop();
        }

        OutputDebugStringA(pop_one.c_str()); //OutputDebugString
        printf(pop_one.c_str());
        IsLog = true;

    } while (mIsRunning);
}
